// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}

// 获取默认配置
function getDefaultConfig() {
    return JSON.stringify({
        title: {
            text: '我的ECharts图表',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '数据系列',
                type: 'line',
                data: [150, 230, 224, 218, 135, 147, 260]
            }
        ]
    }, null, 2);
}

// 获取图表模板
function getChartTemplates() {
    return [
        {
            name: '折线图',
            thumbnail: 'img/templates/line.png',
            config: {
                title: {
                    text: '折线图示例',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'category',
                    data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月']
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '数据1',
                        type: 'line',
                        data: [150, 230, 224, 218, 135, 147, 260]
                    },
                    {
                        name: '数据2',
                        type: 'line',
                        data: [80, 130, 90, 240, 180, 200, 190]
                    }
                ]
            }
        },
        {
            name: '柱状图',
            thumbnail: 'img/templates/bar.png',
            config: {
                title: {
                    text: '柱状图示例',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月']
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '销售额',
                        type: 'bar',
                        data: [120, 200, 150, 80, 70, 110, 130]
                    }
                ]
            }
        },
        {
            name: '饼图',
            thumbnail: 'img/templates/pie.png',
            config: {
                title: {
                    text: '饼图示例',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
                },
                series: [
                    {
                        name: '访问来源',
                        type: 'pie',
                        radius: '50%',
                        center: ['50%', '60%'],
                        data: [
                            {value: 335, name: '直接访问'},
                            {value: 310, name: '邮件营销'},
                            {value: 234, name: '联盟广告'},
                            {value: 135, name: '视频广告'},
                            {value: 1548, name: '搜索引擎'}
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            }
        },
        {
            name: '散点图',
            thumbnail: 'img/templates/scatter.png',
            config: {
                title: {
                    text: '散点图示例',
                    left: 'center'
                },
                xAxis: {},
                yAxis: {},
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return `(${params.value[0]}, ${params.value[1]})`;
                    }
                },
                series: [{
                    symbolSize: 10,
                    data: [
                        [10.0, 8.04],
                        [8.0, 6.95],
                        [13.0, 7.58],
                        [9.0, 8.81],
                        [11.0, 8.33],
                        [14.0, 9.96],
                        [6.0, 7.24],
                        [4.0, 4.26],
                        [12.0, 10.84],
                        [7.0, 4.82],
                        [5.0, 5.68]
                    ],
                    type: 'scatter'
                }]
            }
        },
        {
            name: '雷达图',
            thumbnail: 'img/templates/radar.png',
            config: {
                title: {
                    text: '雷达图示例',
                    left: 'center'
                },
                tooltip: {},
                legend: {
                    data: ['预算分配', '实际开销'],
                    bottom: 0
                },
                radar: {
                    indicator: [
                        { name: '销售', max: 6500 },
                        { name: '管理', max: 16000 },
                        { name: '信息技术', max: 30000 },
                        { name: '客服', max: 38000 },
                        { name: '研发', max: 52000 },
                        { name: '市场', max: 25000 }
                    ]
                },
                series: [{
                    name: '预算 vs 开销',
                    type: 'radar',
                    data: [
                        {
                            value: [4300, 10000, 28000, 35000, 50000, 19000],
                            name: '预算分配'
                        },
                        {
                            value: [5000, 14000, 28000, 31000, 42000, 21000],
                            name: '实际开销'
                        }
                    ]
                }]
            }
        },
        {
            name: '热力图',
            thumbnail: 'img/templates/heatmap.png',
            config: {
                title: {
                    text: '热力图示例',
                    left: 'center'
                },
                tooltip: {
                    position: 'top'
                },
                grid: {
                    height: '50%',
                    top: '10%'
                },
                xAxis: {
                    type: 'category',
                    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                    splitArea: {
                        show: true
                    }
                },
                yAxis: {
                    type: 'category',
                    data: ['上午', '中午', '下午', '晚上'],
                    splitArea: {
                        show: true
                    }
                },
                visualMap: {
                    min: 0,
                    max: 10,
                    calculable: true,
                    orient: 'horizontal',
                    left: 'center',
                    bottom: '15%'
                },
                series: [{
                    name: '访问量',
                    type: 'heatmap',
                    data: [
                        [0, 0, 5], [0, 1, 7], [0, 2, 3], [0, 3, 5],
                        [1, 0, 7], [1, 1, 8], [1, 2, 6], [1, 3, 4],
                        [2, 0, 3], [2, 1, 5], [2, 2, 9], [2, 3, 2],
                        [3, 0, 5], [3, 1, 3], [3, 2, 4], [3, 3, 8],
                        [4, 0, 8], [4, 1, 1], [4, 2, 6], [4, 3, 7],
                        [5, 0, 2], [5, 1, 4], [5, 2, 7], [5, 3, 9],
                        [6, 0, 4], [6, 1, 6], [6, 2, 5], [6, 3, 3]
                    ],
                    label: {
                        show: true
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            }
        }
    ];
}

// 应用模板
function applyTemplate(template) {
    editor.setValue(JSON.stringify(template.config, null, 2));
    updateChart();
    
    // 关闭模态框
    const templateModal = bootstrap.Modal.getInstance(document.getElementById('templateModal'));
    templateModal.hide();
}

// 显示模板选择
function showTemplates() {
    const templateContainer = document.getElementById('templateContainer');
    templateContainer.innerHTML = '';
    
    // 添加模板
    const templates = getChartTemplates();
    templates.forEach((template, index) => {
        const col = document.createElement('div');
        col.className = 'col-md-4 mb-3';
        
        const card = document.createElement('div');
        card.className = 'card h-100 template-card';
        card.style.cursor = 'pointer';
        card.onclick = function() {
            applyTemplate(template);
        };
        
        const img = document.createElement('div');
        img.className = 'card-img-top template-preview';
        img.style.height = '150px';
        img.style.backgroundColor = '#f8f9fa';
        img.style.display = 'flex';
        img.style.alignItems = 'center';
        img.style.justifyContent = 'center';
        
        const icon = document.createElement('i');
        icon.className = getTemplateIcon(template.name);
        icon.style.fontSize = '3rem';
        icon.style.color = '#0d6efd';
        
        img.appendChild(icon);
        
        const cardBody = document.createElement('div');
        cardBody.className = 'card-body';
        
        const title = document.createElement('h5');
        title.className = 'card-title';
        title.textContent = template.name;
        
        cardBody.appendChild(title);
        card.appendChild(img);
        card.appendChild(cardBody);
        col.appendChild(card);
        
        templateContainer.appendChild(col);
    });
    
    // 显示模态框
    const templateModal = new bootstrap.Modal(document.getElementById('templateModal'));
    templateModal.show();
}

// 获取模板图标
function getTemplateIcon(templateName) {
    const iconMap = {
        '折线图': 'bi bi-graph-up',
        '柱状图': 'bi bi-bar-chart',
        '饼图': 'bi bi-pie-chart',
        '散点图': 'bi bi-scatter-chart',
        '雷达图': 'bi bi-bullseye',
        '热力图': 'bi bi-grid-3x3'
    };
    
    return iconMap[templateName] || 'bi bi-graph-up';
}